package org.bjf.modules.wechat.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;

public class WechatUtils {
    /*
     * 规则描述
     *1. 将token、timestamp、nonce三个参数进行字典序排序
     *2. 将三个参数字符串拼接成一个字符串进行sha1加密
     *3. 获得加密后的字符串可与signature对比，标识该请求来源于微信
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String token = "prince";
        ArrayList<String> list = new ArrayList();
        list.add(nonce);
        list.add(timestamp);
        list.add(token);
        Collections.sort(list);
        StringBuilder sb = new StringBuilder();
        list.forEach(sb::append);
        String result = sb.toString();
        String sha1 = DigestUtils.sha1Hex(result);
        System.out.println(String.format("sha1:%s,signature:%s", sha1, signature));
        return signature.equals(sha1);
    }
}